<?php

namespace App\Models;

use App\Exceptions\GeneralException;
use App\Facades\CommonPlatformRequestFacade;
use App\Facades\MoneyPlatformRequestFacade;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

/**
 * App\Models\UserChangeBankCardRecord
 *
 * @property int $id
 * @property int $nfsp_user_id 资方用户id
 * @property string $real_name 持卡人姓名
 * @property string $phone_num 预留手机号
 * @property int $cert_type 证件类型：1 身份证,2 因私护照,3 因公护照,4 香 港永久性居民身份证,5 澳门永久性居 民身份证,6 港澳居民来往内地通行 证,7 台湾居民来往大陆通行证,8 外国 人永久居住证,9 其他证件
 * @property string $cert_num 用户证件号码
 * @property string $card_num 用户银行卡号码
 * @property string $line_number 联行号
 * @property string $bank_name 银行卡信息
 * @property string $bank_code 银行编码
 * @property string $purpose 换卡目的
 * @property string $loan_id 新流订单id，当前只有用户放款需要换卡收款时才会有
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereBankCode($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereBankName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereCardNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereCertNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereCertType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereLineNumber($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereLoanId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereNfspUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord wherePhoneNum($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord wherePurpose($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereRealName($value)
 * @mixin \Eloquent
 * @property int $user_id 用户id
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereUserId($value)
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\UserChangeBankCardRecord whereUpdatedAt($value)
 */
class UserChangeBankCardRecord extends Model
{
    protected $guarded = [
        'id'
    ];

    /**
     * 用途：放款
     */
    const PURPOSE_LOAN = 1;

    /**
     * 用途还款
     */
    const PURPOSE_REPAY = 2;

    const PURPOSE_TEXT = [
        self::PURPOSE_LOAN => 'LOAN',
        self::PURPOSE_REPAY => 'REPAY',
    ];


    const PURPOSE_CH_TEXT = [
        self::PURPOSE_LOAN => '收款',
        self::PURPOSE_REPAY => '还款',
    ];


    /**
     * Description: 用户换卡
     * Author: liuju
     * DateTime: 2019-01-11 11:55
     * @param UserBankCard $card
     * @param $purpose 1 时放款 2是还款
     * @param $summaryId
     * @return mixed
     * @throws GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function changeCard(UserBankCard $card, $purpose, $summaryId)
    {
        if(empty($card)){
            throw  new GeneralException('换卡模型为空');
        }
        if (!in_array($purpose, array_keys(self::PURPOSE_TEXT))) {
            throw   new GeneralException('换卡目的格式不正确');
        }

        $user = auth('api')->user();
        if(!$user->nfsp_user_id && !$user->old_xinliu_id){
            throw new  GeneralException('此借款订单不支持换卡操作，请联系客服或线下还款');
        }
        $valid = $user->valid;
        if (!$valid) {
            throw   new GeneralException('该用户尚未实名认证或认证信息已过期');
        }
        //获取下银行卡的最新信息
        $verifyCard  = CommonPlatformRequestFacade::bankCode($card->card_num);
        Log::debug('银行卡信息是:'.json_encode($verifyCard,JSON_UNESCAPED_UNICODE));
        if(!$verifyCard || $verifyCard['code'] !== '01'){
            throw  new GeneralException($verifyCard['message']);
        }
        $cardInfo = $verifyCard['data'];
        $xinLiuUserId = $user->nfsp_user_id;  //默认使用卡贷2的新流用户id
        $type = RepaySummary::DATA_TYPE_ONE;
        //这个人要换还款卡
        if($summaryId){
            //此人有一笔属于旧卡贷未还完的借款,则使用卡贷1的新流用户id和商户号
            $transId = RepaySummary::where(['uid'=>$user->id,'status'=>RepaySummary::STATUS_ONE,'id'=>$summaryId])->value('trans_id');
            if($transId && $user->old_xinliu_id){
                $xinLiuUserId = $user->old_xinliu_id;
                $type = RepaySummary::DATA_TYPE_TWO;
            }
        }

        $params = [
            'user_id' => $xinLiuUserId,
            'real_name' => $card->card_username,
            'card_num' => $card->card_num,
            'bank_code' => $cardInfo['bank_code'],
            'bank_name' => $cardInfo['bank_name'],
            'phone_num' => $card->phone_num,
            'cert_num' => $valid->num,
            'cert_type' => '1',
            'protocolNo' => $card->hold_agreement_num ?? '',
            'protocolDate' => Carbon::now()->format('Y-m-d H:i'),
            'purpose' => self::PURPOSE_TEXT[$purpose],
        ];
        Log::debug('换卡增加协议号user_id'.$user->id.'参数为=>'.json_encode($params,JSON_UNESCAPED_UNICODE));

        $res = MoneyPlatformRequestFacade::changeBankCard($params,$type);
        unset($params['protocolNo']);//删除这个下面用不到的参数 防止数据库报错
        unset($params['protocolDate']);//删除这个下面用不到的参数 防止数据库报错
        Log::debug('「换卡结果」'.json_encode($res,JSON_UNESCAPED_UNICODE).'新流id:'.$xinLiuUserId.'参数为:'.json_encode($params,JSON_UNESCAPED_UNICODE).'type:'.$type.'userid:'.$user->id);
        if($res['code'] === '01'){
            $data = !empty($res['data']) ? $res['data'] : [];
            if(!empty($data)){
                $params['line_number'] = $data['loanBankCardNo'];
            }
            $params['user_id'] = $user->id;
            $params['purpose'] = $purpose;
            $globalStatus = UserGlobal::where('uid',$user->id)->where('global_status',UserGlobal::STATUS_LOAN_CHANGE_CARD)->value('uid');
            //如果用户换卡目的为还款，卡类型为储蓄卡，用户当前处于需要换卡的阶段
            if($purpose == UserChangeBankCardRecord::PURPOSE_LOAN  && $card->is_credit == UserBankCard::CREDIT_NO  && $globalStatus){
                UserGlobal::where('uid',$user->id)->update([
                    'global_status' => UserGlobal::STATUS_LOAN_MONEY_PROCESSING
                ]);
                $loanId = LoanApply::where('user_id',$user->id)->where('loan_status',LoanApply::LOAN_CHANGE_CARD)->orderByDesc('id')->value('loan_id');
                if($loanId){
                    $params['loan_id'] = $loanId;
                }
            }
            //记录换卡
            UserChangeBankCardRecord::create($params);
            if($card->is_credit == UserBankCard::CREDIT_NO){
                User::UpdateUsingBankCard($card);
            }
        }
        return $res;
    }
}
